﻿'use strict';

QuotingToolApp
 .controller('QuoteController', ['$scope', '$location', '$route', '$routeParams', '$uibModal', '$filter', 'CommonServices', 'QuoteData', 'QuoteServices', 'notifications', 'contractsData',
     function ($scope, $location, $route, $routeParams, $uibModal, $filter, CommonServices, QuoteData, QuoteServices, notifications, contractsData) {

         var self = this;        

       //  self.itemsByPage = 5;                   

        //===========================================  BASIC QUOTE FUNCTIONS ===================================
         self.init = function () {                        
             self.showDiv = false;

             self.quote = {};
             self.quoteChanged = {
                 Header: {},
                 Lines: [],
                 SubLines: [],
             };
             
             //table tabs defaults
             self.SLTab = 1;

             //presentation flags defaults
             self.headerExpanded = false;                              

             //self.initSelectOptions();

             //get inital contracts data for the new quote or get existing quote            
             if ($routeParams.quoteNumber) {

                 self.getQuote($routeParams.quoteNumber);
                 self.screenTitle = "Edit quote";
             }
             else if(CommonServices.newQuoteParamsObj.quoteID)
             {
                 $location.path("/quote/"+CommonServices.newQuoteParamsObj.quoteID)
             }
             else if (CommonServices.newQuoteParamsObj.ContractIDs) {
                 self.headerExpanded = true;
                 self.createNewQuote();
                 self.screenTitle = "Create new quote";
             }

             $scope.$watch("QC.quote.Header",
                 function (newValue, oldValue) {
                     if (newValue && oldValue) {

                         self.quoteChanged.Header = self.quote.Header;
                         self.updateQuote();

                     }
                 }, true);
         };

         self.closeFilter = function () {             
             self.showDiv = false;
         }

         self.initSelectOptions = function(defaults){
             self.selectOptions = {
                 CUSTOMER_INSTALLED_AT: [],
                 CUSTOMER_SOLD_TO: [],
                 CUSTOMER_BILL_SHIP_TO: [],
                 BILL_TO_SITE: [],
                 SHIP_TO_SITE: [],
                 CURRENCY_CODE: [],
                 OPERATING_UNIT_ID: [],
                 ONE_LINE_DISCOUNT_TYPE: [{ name: '%', value: 'PCT' }, { name: 'Amount', value: 'AMT' }],
                 MULTI_YEAR_INCENTIVE: [],
                 AUTO_INVOICING_FLAG: [{ name: 'Yes', value: 'Y' }, { name: 'No', value: 'N' }],
                 MAINTENANCE_ITEMS: []
             };                         
             
             for(var i=0;i<=5;i++)
                 self.selectOptions.MULTI_YEAR_INCENTIVE.push( {name: i+'%', value: i.toString()});          

             //load currencies field options             
             CommonServices.getCurrencies()
                        .$promise
                        .then(function (results) {
                            self.selectOptions.CURRENCY_CODE = results;

                        })
                        .catch(function (response) { notifications.showError("CURRENCY_CODE load failed"); });


             //load operating units
             QuoteServices.getOperatingUnits()
                 .$promise
                 .then(function (results) {
                     self.selectOptions.OPERATING_UNIT_ID = results;
                     if (defaults) {
                         if (defaults.OPERATING_UNIT.length == 1) {
                             self.quote.Header.OPERATING_UNIT_ID = self.getKeyByValue(defaults.OPERATING_UNIT[0], self.selectOptions.OPERATING_UNIT_ID);
                         }
                     }

                 })
                 .catch(function (response) { notifications.showError("OPERATING_UNIT_ID load failed"); });
            

             //load CUSTOMER_INSTALLED_AT options
             var searchParams = {
                 "headerId": self.quote.Header.HEADER_ID,
                 "customerType": 'INSTALLED_AT'
             };
             QuoteServices.getQuoteCustomers(searchParams)
                        .$promise
                        .then(function (results) {
                            self.selectOptions.CUSTOMER_INSTALLED_AT = results;
                            if (defaults) {
                                if (defaults.INSTALLED_AT_CUSTOMER.length == 1) {
                                    self.quote.Header.INSTALLED_AT_PARTY_ID  = self.getKeyByValue(defaults.INSTALLED_AT_CUSTOMER[0], self.selectOptions.CUSTOMER_INSTALLED_AT);
                                }
                            }                            
                        })
                        .catch(function (response) { notifications.showError("CUSTOMER_INSTALLED_AT load failed"); });

             ////load CUSTOMER_SOLD_TO LOV
             searchParams.customerType = 'SOLD_TO';  
             QuoteServices.getQuoteCustomers(searchParams)
                        .$promise
                        .then(function (results) {
                            self.selectOptions.CUSTOMER_SOLD_TO = results;
                            if (defaults) {
                                if (defaults.SOLD_TO.length == 1) {
                                    self.quote.Header.SOLD_TO_PARTY_ID = self.getKeyByValue(defaults.SOLD_TO[0], self.selectOptions.CUSTOMER_SOLD_TO);

                                    //load bill to and ship to customer optons according to sold to default value
                                    self.getBillToShipToCustomersOptions();
                                    self.getBillToShipToAddressOptions("BILL_TO");
                                    self.getBillToShipToAddressOptions("SHIP_TO");
                                }
                            }
                        })
                        .catch(function (response) { notifications.showError("CUSTOMER_SOLD_TO load failed"); });

            
         };

         self.getBillToShipToCustomersOptions = function(){
             var searchParams = {                    
                 SOLD_TO_PARTY_ID: self.quote.Header.SOLD_TO_PARTY_ID,
                 OPERATING_UNIT_ID: (self.quote.Header.OPERATING_UNIT_ID) || 'null'
             };
                          
            // if (self.quote.Header.OPERATING_UNIT_ID) searchParams.OPERATING_UNIT_ID = self.quote.Header.OPERATING_UNIT_ID;
             

             //load CUSTOMER_BILL_SHIP_TO options
             if (searchParams.SOLD_TO_PARTY_ID) {
                 QuoteServices.getBillToShipToCustomers(searchParams)
                            .$promise
                            .then(function (results) {
                                self.selectOptions.CUSTOMER_BILL_SHIP_TO = results;

                            })
                            .catch(function (response) { notifications.showError("CUSTOMER_BILL_SHIP_TO load failed"); });
             }
         };
              
         self.getBillToShipToAddressOptions = function (siteUseType) {
             var searchParams = {
                 // custaccountid: searchParams.custAccountId, siteusetype: searchParams.siteUseType, operatingunitid: searchParams.OPERATING_UNIT_ID
                 custAccountId: (siteUseType=='BILL_TO') ? self.quote.Header.BILL_TO_CUSTOMER_ID : self.quote.Header.SHIP_TO_CUSTOMER_ID,
                 siteUseType: siteUseType,  //'BILL_TO',
                 OPERATING_UNIT_ID: (self.quote.Header.OPERATING_UNIT_ID) || 'null'
             };

             if (searchParams.custAccountId) {
                 //load BILL_TO_SITE options
                 QuoteServices.getBillToShipToAddress(searchParams)
                            .$promise
                            .then(function (results) {
                                if(siteUseType=='BILL_TO')
                                    self.selectOptions.BILL_TO_SITE = results;
                                else
                                    self.selectOptions.SHIP_TO_SITE = results;
                            })
                            .catch(function (response) { notifications.showError("BILL_TO_SHIP_TO_SITE load failed"); }
                        );
             }
         };
                       
         self.initHeaderGetters = function () {
             self.quote.Header.getters = {
                 CREATION_DATE: function () {
                     if (angular.isDefined(self.quote.Header.CREATION_DATE))
                         return self.formatDate(self.quote.Header.CREATION_DATE);
                 },
                 LAST_UPDATE_DATE: function () {
                     if (angular.isDefined(self.quote.Header.LAST_UPDATE_DATE))
                         return self.formatDate(self.quote.Header.LAST_UPDATE_DATE);
                 },
                 QUOTE_DATE: function () {
                     if (angular.isDefined(self.quote.Header.QUOTE_DATE))
                         return self.formatDate(self.quote.Header.QUOTE_DATE);
                 },
                 START_DATE: function () {
                     if (angular.isDefined(self.quote.Header.START_DATE))
                         return self.formatDate(self.quote.Header.START_DATE);
                 },
                 END_DATE: function () {
                     if (angular.isDefined(self.quote.Header.END_DATE))
                         return self.formatDate(self.quote.Header.END_DATE);
                 },
                 TOTAL_AMOUNT: function () {
                     if (angular.isDefined(self.quote.Header.TOTAL_AMOUNT))
                         return parseFloat(self.quote.Header.TOTAL_AMOUNT);
                 },
                 ACV: function () {
                     if (angular.isDefined(self.quote.Header.ACV))
                         return parseFloat(self.quote.Header.ACV);
                 },
                 ONE_LINE_DISCOUNT: function (oneLineDiscountNew) {
                     if (angular.isDefined(self.quote.Header.ONE_LINE_DISCOUNT))
                         //    return parseFloat(self.quote.Header.ONE_LINE_DISCOUNT);
                         return arguments.length>0 ? (self.quote.Header.ONE_LINE_DISCOUNT = oneLineDiscountNew) : parseFloat(self.quote.Header.ONE_LINE_DISCOUNT);
                 }
             };

         };

         self.initSublinesGetters = function(){
                 
             self.quote.SubLines.getters = {                
                 START_DATE: function (row) {
                     if (angular.isDefined(row.START_DATE))
                         return self.formatDate(row.START_DATE);
                 },
                 END_DATE: function (row) {
                     if (angular.isDefined(row.END_DATE))
                         return self.formatDate(row.END_DATE);
                 },
                 PRODUCT_ORIG_SHIP_DATE: function (row) {
                     if (angular.isDefined(row.PRODUCT_ORIG_SHIP_DATE))
                         return self.formatDate(row.PRODUCT_ORIG_SHIP_DATE);
                 },
                 TOTAL_LIST_PRICE: function(row){
                     if (angular.isDefined(row.TOTAL_LIST_PRICE))
                         return parseFloat(row.TOTAL_LIST_PRICE);
                 },
                 TOTAL_NET_PRICE: function(row){
                     if (angular.isDefined(row.TOTAL_NET_PRICE))
                         return parseFloat(row.TOTAL_NET_PRICE);
                 },
                 BASE_MAINTENANCE_PRICE: function(row){
                     if (angular.isDefined(row.BASE_MAINTENANCE_PRICE))
                         return parseFloat(row.BASE_MAINTENANCE_PRICE);
                 },
                 PREVIOUS_AMOUNT: function(row){
                     if (angular.isDefined(row.PREVIOUS_AMOUNT))
                         return parseFloat(row.PREVIOUS_AMOUNT);
                 },
                 MAINT_PRICE_INCLUDING_COL: function (row) {
                     if (angular.isDefined(row.MAINT_PRICE_INCLUDING_COL))
                         return parseFloat(row.MAINT_PRICE_INCLUDING_COL);
                 },
                 ANNUAL_MAINT_PRICE_INCL_COL: function (row) {
                     if (angular.isDefined(row.ANNUAL_MAINT_PRICE_INCL_COL))
                         return parseFloat(row.ANNUAL_MAINT_PRICE_INCL_COL);
                 }
             }

         };         
        
         self.createNewQuote = function () {
             var defaults = {
                 INSTALLED_AT_CUSTOMER: [],
                 SOLD_TO: [],
                 OPERATING_UNIT: []
             };            

             //create new quote based on the contracts parameter              
             var results = QuoteData.save(CommonServices.newQuoteParamsObj, function () {
                 self.quote = results;
                 CommonServices.newQuoteParamsObj.quoteID = self.quote.Header.HEADER_ID;

                 self.initHeaderGetters();            //cannot init getters before objects loaded              
                               
                 //set default values
                 if (CommonServices.newQuoteParamsObj.selectedAccountParam) {
                     self.quote.Header.OPPORTUNITY_NUMBER = CommonServices.selectedAccountParam.OppID
                     //self.quote.PRIMARY_QUOTE = contractsData.selectedAccount.????;         //*********************TO BE COMPLETED*********************
                 }

                 //collect defaults from the contracts collection
                 CommonServices.newQuoteParamsObj.ContractIDs.forEach(function (element, index, array) {
                     if (element.INSTALLED_AT_CUSTOMER != '')
                         if (defaults.INSTALLED_AT_CUSTOMER.indexOf(element.INSTALLED_AT_CUSTOMER) == -1)
                             defaults.INSTALLED_AT_CUSTOMER.push(element.INSTALLED_AT_CUSTOMER);

                     if (element.SOLD_TO != '')
                         if (defaults.SOLD_TO.indexOf(element.SOLD_TO) == -1)
                             defaults.SOLD_TO.push(element.SOLD_TO);

                    

                     if (element.OPERATING_UNIT != '')
                         if (defaults.OPERATING_UNIT.indexOf(element.OPERATING_UNIT) == -1)
                             defaults.OPERATING_UNIT.push(element.OPERATING_UNIT);
                 });
                 
                 self.initSelectOptions(defaults);


                 self.DisableDiscountButtonFlag = false;
                 self.DisableRevertButtonFlag = true;

             });
             
         };         
         
         self.getQuote = function (quoteID) {
             var results = QuoteData.get({ id: quoteID, lineid: 'null' }, function () {
                 self.quote = results;
                 self.initHeaderGetters();        //cannot init getters before objects loaded
                 self.initSelectOptions();
                 self.getBillToShipToCustomersOptions();
                 self.getBillToShipToAddressOptions("BILL_TO");
                 self.getBillToShipToAddressOptions("SHIP_TO");
                 
                 if (self.quote.Header.ONE_LINE_DISCOUNT || self.quote.Header.MULTI_YEAR_INCENTIVE) {
                     self.DisableDiscountButtonFlag = true;
                     self.DisableRevertButtonFlag = false;
                 }
                 else {
                     self.DisableDiscountButtonFlag = false;
                     self.DisableRevertButtonFlag = true;
                 }
             });
         };        
      
         self.updateQuote = function (msgText) {

             var results = QuoteData.update(self.quoteChanged.HEADER_ID, self.quoteChanged, function () {
                 
                 //console.log(results);                 
                 self.quoteChanged = {};        //reset changes object
                 if (msgText) notifications.showSuccess(msgText);

                 //show updated info on the screen
                 
                 if (results.SubLines) {
                     if (results.SubLines.length > 0) self.showUpdatedSublines(results.SubLines);
                 }
                 if (results.Lines) {
                     if (results.Lines.length > 0) self.showUpdatedLines(results.Lines);
                 }
                 if (results.Header) {
                     self.showUpdatedHeader(results.Header);
                 }
                 console.log('updated');

             }); //saves an entry.
         };
         
         //===========================================  BUTTONS =================================================

         self.toggleHeader = function () {
             self.headerExpanded = !self.headerExpanded
         };

         self.searchOpportunity = function () {
             $scope.selectedOpp = "";

             var modalInstance = $uibModal.open({
                 animation: $scope.animationsEnabled,
                 templateUrl: 'templates/searchopportunity.html',
                 controller: 'SearchOpportunityController',
                 size: 'lg'
             });

             modalInstance.result.then(function (selectedOpp) {
                 self.quote.Header.OPPORTUNITY_NUMBER = selectedOpp;
             }, function () {
                 //console.log('Modal dismissed at: ' + new Date());
             });

         }

         self.revertDiscount = function () {
             var searchParams = {
                 "headerId": self.quote.Header.HEADER_ID
             };

             QuoteServices.revertDiscount(searchParams)
            .$promise
            .then(function (results) {

                if (results.Lines) {
                    if (results.Lines.length > 0) self.showUpdatedLines(results.Lines);
                }
                if (results.Header) {
                    self.showUpdatedHeader(results.Header);

                    self.quote.Header.ONE_LINE_DISCOUNT_TYPE = results.Header.ONE_LINE_DISCOUNT_TYPE;
                    self.quote.Header.ONE_LINE_DISCOUNT = results.Header.ONE_LINE_DISCOUNT;
                    self.quote.Header.PRE_PAID_INDICATION =results.Header.PRE_PAID_INDICATION == 'Y' ? true : false;
                    self.quote.Header.MULTI_YEAR_INCENTIVE = results.Header.MULTI_YEAR_INCENTIVE;                    
                    
                    self.DisableDiscountButtonFlag = false;
                    self.DisableRevertButtonFlag = true;
                }
                for (var i in self.quote.Lines) {
                    if (self.quote.Lines[i].isSelected) {
                        var results = QuoteData.get({ id: self.quote.Header.HEADER_ID, lineid: self.quote.Lines[i].LINE_ID }, function () {
                            self.quote.SubLines = results.SubLines;
                            self.initSublinesGetters();
                        });
                    }
                }
                // $route.reload();
            })
            .catch(function (response) { notifications.showError("Revert discount operation failed"); });
         };

         self.setDiscount = function (discountform) {
             
             if (discountform.$valid) {
             var searchParams = {
                 headerid: self.quote.Header.HEADER_ID,
                 OneLineDiscountType: (self.quote.Header.ONE_LINE_DISCOUNT_TYPE) ? self.quote.Header.ONE_LINE_DISCOUNT_TYPE : 'null',
                 OneLineDiscount: (self.quote.Header.ONE_LINE_DISCOUNT) ? self.quote.Header.ONE_LINE_DISCOUNT : 'null',
                 PrePaidIndication: self.quote.Header.PRE_PAID_INDICATION == 'Y' ? self.quote.Header.PRE_PAID_INDICATION : 'null',
                 MultiYearIncentive: (self.quote.Header.MULTI_YEAR_INCENTIVE) ? self.quote.Header.MULTI_YEAR_INCENTIVE : 'null'
             };



             if (self.quote.Header.ONE_LINE_DISCOUNT_TYPE == '' && self.quote.Header.ONE_LINE_DISCOUNT == '' && self.quote.Header.MULTI_YEAR_INCENTIVE == '') {
                 notifications.showError("at last two parameters should be sent");
                 return;
             }

             QuoteServices.setDiscount(searchParams) //todo: add the rest of the params
            .$promise
            .then(function (results) {
               
                if (results.Lines) {
                    if (results.Lines.length > 0) self.showUpdatedLines(results.Lines);
                }
                if (results.Header) {
                    self.showUpdatedHeader(results.Header);

                }

                for (var i in self.quote.Lines) {
                    if (self.quote.Lines[i].isSelected) {
                        var results = QuoteData.get({ id: self.quote.Header.HEADER_ID, lineid: self.quote.Lines[i].LINE_ID }, function () {
                            self.quote.SubLines = results.SubLines;
                            self.initSublinesGetters();
                        });
                    }
                }


                self.DisableDiscountButtonFlag = true;
                self.DisableRevertButtonFlag = false;               

            })
            .catch(function (response) { notifications.showError("Set discount operation failed"); });
             }

         };

         self.copyQuote = function () {
             var searchParams = {
                 "headerId": self.quote.Header.HEADER_ID
             };

             QuoteServices.copyQuote(searchParams)
            .$promise
            .then(function (results) {
                $location.path("/quote/" + results.Header.HEADER_ID)

            })
            .catch(function (response) { notifications.showError("Copy quote operation failed"); });
         };

         self.finish = function () {

             var successMsg = "Quote saved in DRAFT status"
             self.quote.Header.QUOTE_STATUS = 'DRAFT';
             self.quoteChanged.Header = self.quote.Header;
             // self.quoteChanged.Header.IS_UPDATED = 1;             

             self.updateQuote(successMsg);
             //// $location.path("/myQuotes");
         }         

         self.reload = function () {

             $route.reload();

             //self.getQuote(self.quote.Header.HEADER_ID);                         

         }

         self.produceProposal = function (excelform) {

             document.getElementById('excelform').submit();

             //$http({
             //    method: 'POST',
             //    url: 'http://quotingtool/Excel',
             //    data: $.param($scope.formData),  // pass in data as strings
             //    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }  // set the headers so angular passing info as form data (not request payload)
             //})
             //.success(function (data) {
             //    console.log(data);

             //    if (!data.success) {
             //        // if not successful, bind errors to error variables
             //        $scope.errorName = data.errors.name;
             //        $scope.errorSuperhero = data.errors.superheroAlias;
             //    } else {
             //        // if successful, bind success message to message
             //        $scope.message = data.message;
             //    }
             //});


             //quoteData.getProposalFile();
         };

         self.generateContract = function () {
             var searchParams = {
                 "headerId": self.quote.Header.HEADER_ID
             };

             contractsData.generatecontract(searchParams)
            .$promise
            .then(function (results) {
                //console.log(JSON.stringify(results));
            })
            .catch(function (response) { notifications.showError("Generate contract operation failed"); });
         };

         self.routeForApproval = function () {
             var searchParams = {
                 "headerId": self.quote.Header.HEADER_ID
             };

             QuoteServices.CreateQuote(searchParams)
            .$promise
            .then(function (results) {
                notifications.showSuccess("Create Quote operation Success");
            })
            .catch(function (response) { notifications.showError("Create Quote operation failed"); });
         };

         self.goBack = function () {
             var modalInstance = $uibModal.open({
                 animation: $scope.animationsEnabled,
                 templateUrl: 'templates/Message.html?id='+Math.random(100),
                 controller: 'MessageController',
                 size: 'sm',
                 resolve: {
                     message: function ()
                     {
                         return "This will delete the generated quote. Do you want to continue?"
                     }
                 }
             });

             modalInstance.result.then(function () {
                 // Delete the specific Quote
                 var results = QuoteData.delete({ id: self.quote.Header.HEADER_ID, lineid: 'null' },
                          function () {

                              notifications.showSuccess("Quote deleted");
                          },
                          function () {
                              notifications.showError("Failed to delete sublines. Please reload your screen and try again.");
                          }); //saves an entry.

                $location.path("/searchContracts");
             }, function () {
                 //console.log('Modal dismissed at: ' + new Date());
             });
             
         };

         //========================================  EDIT TABLE FIELDS FUNCTIONS ================================
        
         self.changeLines = function (newValue, fieldName, index) {
             
             var tblName = fieldName.split(".")[0];
             var fldName = fieldName.split(".")[1];
            
             if (fldName == 'MAINTENANCE_ITEM')
             {
                 self.quote[tblName][index][fldName] = newValue.VALUE;
                 self.quote[tblName][index][fldName + "_ID"] = newValue.KEY;
                 
             } else {

                 self.quote[tblName][index][fldName] = newValue;               
             }

             //if (!self.quoteChanged.Header) {
                 self.quoteChanged.Header = {HEADER_ID: self.quote.Header.HEADER_ID}
                // self.quoteChanged.Header.IS_UPDATED = 0;
             //}

             if (!self.quoteChanged[tblName])
                 self.quoteChanged[tblName] = [];

             var massUpdateFlag = false;
             //mass update for all selected             
             for (var i in self.quote[tblName]) {
                 if (self.quote[tblName][i].isSelected) {
                     if (fldName == 'MAINTENANCE_ITEM') {
                         self.quote[tblName][i][fldName] = newValue.VALUE;
                         self.quote[tblName][i][fldName + "_ID"] = newValue.KEY;

                     } else {

                         self.quote[tblName][i][fldName] = newValue;
                     }
                     
                    // self.quote[tblName][i][fldName] = newValue;
                     self.quoteChanged[tblName].push(self.quote[tblName][i]);
                     massUpdateFlag = true;
                 }
             }
             if (!massUpdateFlag)       //no selected lines updated, save single line only
                 self.quoteChanged[tblName].push(self.quote[tblName][index]);

               self.updateQuote();           

         };

         self.showUpdatedSublines = function (updatedSublines) {

             for (var i in updatedSublines)
             {
                 for (var j in self.quote.SubLines) {
                     if (self.quote.SubLines[j].SUBLINE_ID == updatedSublines[i].SUBLINE_ID) {
                         self.quote.SubLines[j].MAINT_PRICE_INCLUDING_COL = updatedSublines[i].MAINT_PRICE_INCLUDING_COL;
                         self.quote.SubLines[j].ANNUAL_MAINT_PRICE_INCL_COL = updatedSublines[i].ANNUAL_MAINT_PRICE_INCL_COL;
                         self.quote.SubLines[j].DURATION = updatedSublines[i].DURATION;
                     }
                 }
             }
         }
         
         self.showUpdatedLines = function (updatedLines) {

             var newLineIndex = -1;             

             for (var i in updatedLines) {
                 newLineIndex = i;          //set new line index
                 for (var j in self.quote.Lines) {
                     if (self.quote.Lines[j].LINE_ID == updatedLines[i].LINE_ID) {
                         newLineIndex = -1;         //line found, reset new line index
                         self.quote.Lines[j].TOTAL_AMOUNT = updatedLines[i].TOTAL_AMOUNT;                        
                     }
                 }

                 if (newLineIndex != -1)
                     self.quote.Lines.push(updatedLines[newLineIndex]);
             }

             
         }

         self.showUpdatedHeader = function (updatedHeader) {
             self.quote.Header.TOTAL_AMOUNT = updatedHeader.TOTAL_AMOUNT;
             self.quote.Header.START_DATE = updatedHeader.START_DATE;
             self.quote.Header.END_DATE = updatedHeader.END_DATE;
             self.quote.Header.ACV = updatedHeader.ACV;
             self.quote.Header.DURATION = updatedHeader.DURATION;
             self.quote.Header.DURATION_UOM = updatedHeader.DURATION_UOM;
         }

         //========================================  WORK WITH TABLE ROWS =======================================

         self.selectLine = function (row) {
             var index = self.quote.Lines.indexOf(row);
             if (index !== -1) {
                 self.quote.Lines[index].isSelected = !self.quote.Lines[index].isSelected;
                 if (self.quote.Lines[index].isSelected)            //deselect all other rows
                     for (var i in self.quote.Lines)
                         if (i != index) self.quote.Lines[i].isSelected = false;

                 //reload sublines per line
                 var results = QuoteData.get({ id: self.quote.Header.HEADER_ID, lineid: self.quote.Lines[index].LINE_ID }, function () {
                     self.quote.SubLines = results.SubLines;
                     self.initSublinesGetters();
                 });
             }
         };

         self.selectSubline = function (tblName, row, mode) {
             var index = self.quote[tblName].indexOf(row);
             var selectedRow = self.quote[tblName][index];
             if (index !== -1) {
                 //if (mode === 'single') {
                 //    row.isSelected = row.isSelected !== true;
                 //    if (lastSelected) {
                 //        lastSelected.isSelected = false;
                 //    }
                 //    lastSelected = row.isSelected === true ? row : undefined;
                 //} else {
                     self.quote[tblName][index].isSelected = !selectedRow.isSelected;                    
                 //}
                     
             }
             
         };
                
         //self.getSelectedRows = function (lines) {
         //    var selectedItems = [];
         //    for (var i = 0; i < lines.length; i++) {
         //        if (lines[i].isSelected) {
         //            selectedItems.push(lines[i]);
         //        }
         //    }

         //    return selectedItems;
         //};
         
         self.removeSelectedSublines = function () {
             //Get Selected Rows
            // var selectedRows = self.getSelectedRows();
             //Remove Each Selected Row
             for (var i = self.quote.SubLines.length-1; i >= 0; i--) {
                 if (self.quote.SubLines[i].isSelected) {
                     if (self.quote.SubLines[i].SUBLINE_ID != '') {
                         //self.quoteChanged.SubLines.push(self.quote.SubLines);
                         var results = QuoteData.delete({ id: self.quote.Header.HEADER_ID, lineid: self.quote.SubLines[i].SUBLINE_ID },
                           function () {                              

                               notifications.showSuccess("Sublines deleted");

                               if (results.Lines) {
                                   if (results.Lines.length > 0) self.showUpdatedLines(results.Lines);
                               }
                               if (results.Header) {
                                   self.showUpdatedHeader(results.Header);
                               }
                           },
                           function () {
                               notifications.showError("Failed to delete sublines. Please reload your screen and try again.");
                           }); //saves an entry.
                        

                     }
                     self.quote.SubLines.splice(i, 1);                    
                 }
             }

             //if (self.quoteChanged.SubLines.length > 0) {
                
             //    $.each(self.quoteChanged.SubLines, function (key, value) {
             //        QuoteData.delete({ id: null, lineid: value.SUBLINE_ID },
             //           function () {
             //               notifications.showSuccess("Sublines deleted");
             //           },
             //           function () {
             //               notifications.showError("Failed to delete sublines. Please reload your screen and try again.");
             //           }); //saves an entry.
             //    })
             //}
     };

         ////remove to the real data holder
         //self.removeItem = function removeItem(row) {
         //    var index = self.contractsCollection.indexOf(row);
         //    if (index !== -1) {
         //        self.contractsCollection.splice(index, 1);
         //    }
         //};

         //============================== HELP FUNCTIONS ===========================================

         self.getKeyByValue = function (value, optionsArray) {
             for (var i = 0; i < optionsArray.length; i++)
                 if (optionsArray[i].VALUE == value)
                     return optionsArray[i].KEY;
         };
     
         self.formatDate = function (dateStr) {
             var dateOnly = dateStr.split(" ")[0];
             var m = parseInt(dateOnly.split('/')[0]) - 1;
             var d = parseInt(dateOnly.split('/')[1]);
             var y = parseInt(dateOnly.split('/')[2]);

             return Date.UTC(y, m, d);
         };

         //=========================INIT QUOTE CONTROLLER===========================================
         
         self.init();

}])
//.directive('stringToNumber', function () {
//    return {
//        require: 'ngModel',
//        link: function (scope, element, attrs, ngModel) {
//            ngModel.$parsers.push(function (value) {
//                return '' + value;
//            });
//            ngModel.$formatters.push(function (value) {
//                if (value)
//                    return parseFloat(value);
//            });
//        }
//    };
//})